﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Beauty.BLL;
using Beauty.Model;
using WebUI.Areas.Admin.Models;
namespace WebUI.Areas.Admin.Controllers
{
    [CheckUserFilter]
    public class HomeController : Controller
    {
        // GET: Admin/Home
        public ActionResult Index()
        {
            return View();
        }

        #region 展示服务器信息
        public ActionResult WelCome()
        {
            return View(new ServerInfos());
        }

        #endregion

        #region 展示添加套图
        public ActionResult AddPicture()
        {
            //获取分类 供套图选择
            List<picclass> classes = bllClass.DataTableToList(bllClass.GetAllList().Tables[0]);

            ViewData["classes"] = classes;
            return View();
        }

        #endregion

        #region 编辑套图
        public ActionResult EditAlbum(int albumid)
        {
            //获取分类 供套图选择
            List<picclass> classes = bllClass.DataTableToList(bllClass.GetAllList().Tables[0]);
            picalbum album = bllAlbum.GetModel(albumid);
            ViewData["classes"] = classes;
            ViewData["album"] = album;
            return View();
        }

        #endregion
        #region 更新套图
        [HttpPost]
        public ActionResult EditAlbum(string title, string description, int classId, int albumId)
        {
            picalbum album = new picalbum()
            {
                ClassId = classId,
                Title = title,
                Description = description,
                UpdateTime = DateTime.Now,

            };
            if (bllAlbum.Update(title, description, DateTime.Now, classId, albumId))
            {

                return Json(new { msg = "成功！", error = 0 });

            }
            else
            {

                return Json(new { msg = "失败！", error = 1 });

            }


        }
        #endregion

        #region 展示套图中图片
        public ActionResult ShowPicture(int albumId)
        {
            List<picmain> pics = bllMain.GetModelList("AlbumId=" + albumId, true, false);//获取套图所有图片
            ViewData["pics"] = pics;
            return View();
        }


        #endregion

        #region 上传图片
        [HttpPost]
        public ActionResult AddPicture(HttpPostedFileBase file)
        {

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + Path.GetExtension(file.FileName); ;//2016103151034.jpg

            string filePhysicalPath = Server.MapPath("~/Pic/original/" + fileName);
            string smallFilePhysicalPath = Server.MapPath("~/Pic/small/" + fileName);
            string pic = "", error = "";
            try
            {
                file.SaveAs(filePhysicalPath);//保存原图
                Utilities.ImageHelper.MakeThumbnail(filePhysicalPath, smallFilePhysicalPath, 250, 360, "Cut");
                pic = "/Pic/original/" + fileName;
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return Json(new
            {
                pic = fileName,
                error = error
            });


        }

        #endregion

        #region 删除套图
        [HttpPost]
        public ActionResult DeleteAlbum(int id)
        {
            //先删除图片，再删除套图


            List<picmain> pics = bllMain.GetModelList("AlbumId=" + id);
            string picIds = string.Empty;
            foreach (var item in pics)
            {
                picIds += item.PicId + ",";
            }
            if (!string.IsNullOrEmpty(picIds))
            {
                bllMain.DeleteList(picIds);
            }
            //套图的图片删除完毕 接下来删除套图
            if (bllAlbum.Delete(id))
            {
                return Json(new { error = 0, msg = "成功" });
            }
            else
            {
                return Json(new { error = 1, msg = "失败" });
            }

            //bllMain.DeleteList
        }


        [HttpPost]
        public ActionResult DeleteAlbums(string ids)
        {
            //先删除图片，再删除套图
            string[] arrAlbum = ids.Split(',');
            for (int i = 0; i < arrAlbum.Length; i++)
            {
                List<picmain> pics = bllMain.GetModelList("AlbumId=" + arrAlbum[i]);

                string picIds = string.Empty;
                foreach (var item in pics)
                {
                    picIds += item.PicId + ",";
                }
                if (!string.IsNullOrEmpty(picIds))
                {
                    bllMain.DeleteList(picIds);
                }
                //套图的图片删除完毕 接下来删除套图

            }
            if (bllAlbum.DeleteList(ids))
            {
                return Json(new { error = 0, msg = "成功" });
            }
            else
            {
                return Json(new { error = 1, msg = "失败" });
            }



            //bllMain.DeleteList
        }


        #endregion
        #region 删除套图中的图片
        [HttpPost]
        public ActionResult DeletePicture(string paramIds)
        {
            if (bllMain.DeleteList(paramIds))
            {
                return Json(new { error = 0, msg = "成功" });
            }
            else
            {
                return Json(new { error = 1, msg = "失败" });
            }
        }

        #endregion

        #region 添加套图
        [HttpPost]
        public ActionResult SaveAlbum(string title, string description, int classId, string pics)
        {
            //        //title:标题
            //        description: 描述
            //class:0
            //coverId:1
            //file:
            //file:
            //pics:201610031558448080701.jpg
            //pics:201610031558448070688.jpg
            int userid = 1;
            pics = Request.Form["pics"];
            if (pics == null)
            {
                return Json(new { msg = "请上传几张图片吧！", error = 1 });
            }
            picalbum album = new picalbum()
            {
                Title = title,
                Description = description,
                ClassId = classId,
                UserId = userid,
            };
            int albumId = bllAlbum.Add(album, "GetIndentity");
            string[] src = pics.Split(',');
            List<picmain> mains = new List<picmain>();
            for (int i = 0; i < src.Length; i++)
            {
                picmain pic = new picmain()
                {
                    AlbumId = albumId,
                    Userid = userid,
                    Src = src[i],
                    SortId = i + 1
                };
                mains.Add(pic);
            }

            int newPicId = bllMain.Add(mains);
            if (newPicId > 0)
            {
                //图片插入后再去更新下套图的封面
                bllAlbum.Update(albumId, newPicId);//将最后一张图片作为默认封面

                return Json(new { msg = "成功！", error = 0 });
            }
            else
            {
                return Json(new { msg = "图片主表插入失败！", error = 2 });

            }


        }

        #endregion

        #region 添加图片到套图
        [HttpPost]
        public ActionResult AddPictureToAlbum(int albumId)
        {
            string pics = Request.Form["pics"];
            if (pics == null)
            {
                return Json(new { msg = "请上传几张图片吧！", error = 1 });
            }
            //添加图片
            string[] src = pics.Split(',');
            List<picmain> mains = new List<picmain>();
            for (int i = 0; i < src.Length; i++)
            {
                picmain pic = new picmain()
                {
                    AlbumId = albumId,
                    Userid = 1,
                    Src = src[i],
                    SortId = i + 1
                };
                mains.Add(pic);
            }

            int newPicId = bllMain.Add(mains);
            if (newPicId > 0)
            {
                return Json(new { msg = "成功！", error = 0 });
            }
            else
            {
                return Json(new { msg = "插入失败！", error = 2 });

            }


        }

        #endregion
        #region 展示套图列表
        public ActionResult AlbumList()
        {
            string action = Request["action"];
           
            List<picalbum> albums ;
            List<picclass> classes = bllClass.DataTableToList(bllClass.GetAllList().Tables[0]);
            if (string.IsNullOrEmpty(action))
            {
                albums = bllAlbum.DataTableToList(bllAlbum.GetAllList().Tables[0]);
            }
            else
            {
                switch (action)
                {
                    case "date":
                        
                        albums = bllAlbum.GetModelList(string.Format("AddTime BETWEEN '{0}' AND  '{1}'", Request["start"], Request["end"]));
                        break;
                    default:
                        albums = new List<picalbum>();
                        break;
                }
            }
          
            ViewData["classes"] = classes;
            ViewData["albums"] = albums;

            return View(albums);
        }

        public ActionResult Search(string action)
        {
            List<picalbum> albums;
            List<picclass> classes = bllClass.DataTableToList(bllClass.GetAllList().Tables[0]);

            switch (action)
            {
                case "date":
                    DateTime start = DateTime.Parse(Request["start"]);
                    DateTime end = DateTime.Parse(Request["end"]);
                    albums = bllAlbum.GetModelList(string.Format("AddTime BETWEEN '{0}' AND  '{1}'", start, end));
                    break;
                default:
                    albums = new List<picalbum>();
                    break;
            }
            ViewData["classes"] = classes;
            ViewData["albums"] = albums;

            return View(albums);

        }
        #endregion
        public ActionResult DataTablesTest()
        {
            return View();
        }
        public static int temp { get; set; }
        public ActionResult GetData()
        {




            //var data = new List<dynamic>();
            //for (int i = start; i < start + length; i++)
            //{
            //    data.Add(new { name = "按屌丝" + i, sex = "男" });
            //}
            List<picalbum> albums = bllAlbum.DataTableToList(bllAlbum.GetAllList().Tables[0]);

            var ss = new
            {
                Jsondata = albums,
            };

            return Content(Utilities.JsonHelper.T2JSON(ss));
            //return Json(ss,JsonRequestBehavior.AllowGet);

        }

        picclassBLL bllClass = new picclassBLL();
        picmainBLL bllMain = new picmainBLL();
        picalbumBLL bllAlbum = new picalbumBLL();

        #region Expand
        public ActionResult GetClassifyByAlbumId(int albumid)
        {
            picalbum album = bllAlbum.GetModel(albumid);
            picclass nowEntity = bllClass.GetModel((int)album.ClassId);
            return Content(nowEntity.ClassId.ToString());
        }
        #endregion
    }






    public class ServerInfos
    {
        public string PCName { get { return Models.ServerUtil.GetServerName(); } }
        public string IP { get { return Models.ServerUtil.GetServerIp(); } }
        public string Domain { get { return Models.ServerUtil.GetDomainName(); } }
        public string Port { get { return Models.ServerUtil.GetServerPort(); } }
        public string IISVersion { get { return Models.ServerUtil.GetServerSoftware(); } }
        public string AbsolutePath { get { return HttpContext.Current.Request.MapPath(HttpContext.Current.Request.Path); } }
        public string OperationSys { get { return Environment.OSVersion.VersionString; } }
        public string ScriptTimeout { get { return HttpContext.Current.Server.ScriptTimeout.ToString(); } }
        public string DotNetVersion { get { return Environment.Version.Major.ToString(); } }
        public string NowTime { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString(); } }
        public string CPUNumber { get { return Environment.ProcessorCount.ToString(); } }
        public string CPUType { get { return Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER"); } }
        /// <summary>
        /// 获取系统启动后经过的毫秒数。
        /// </summary>
        public string TickCount { get { return ((Environment.TickCount / 1000) / 60).ToString(); } }
        /// <summary>
        /// 获取当前已登录到 Windows 操作系统的人员的用户名。
        /// </summary>
        public string UserName { get { return Environment.UserName; } }
        public string MachineName { get { return Environment.MachineName; } }
        public bool Is64BitOperatingSystem { get { return Environment.Is64BitOperatingSystem; } }

        public int SessionCount { get { return HttpContext.Current.Session.Count; } }
        public string ACCEPT_LANGUAGE { get { return Models.ServerUtil.GetAcceptLanguage(); } }
        public string SystemPath { get { return Models.ServerUtil.GetSystemPath(); } }

    }
}